package com.ITArmy.controller;

import com.ITArmy.beans.*;
import com.ITArmy.beans.Shows.Book;
import com.ITArmy.beans.Shows.ReadSerialize;
import com.ITArmy.common.ServerResponse;
import com.ITArmy.controller.base.BaseController;
import com.ITArmy.dao.BlogMapper;
import com.ITArmy.dao.CommentMapper;
import com.ITArmy.dao.ConfigsMapper;
import com.ITArmy.dao.OrderMapper;
import com.ITArmy.service.*;
import com.ITArmy.util.GetUserSession;
import com.ITArmy.util.SendEmail;
import com.sun.istack.internal.logging.Logger;
import com.sun.xml.internal.ws.api.model.CheckedException;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Api(value = "用户接口层次", tags = "用户接口层次Controller层")
@Controller

@RequestMapping("/user")
public class UserController extends BaseController implements Serializable {
    private static Logger logger = Logger.getLogger(Controller.class);
    GetUserSession getUserSession = new GetUserSession();
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    ConfigsMapper configsMapper;

    @RequestMapping("/uploadPage")
    @ApiOperation(value = "上传图片的接口",
            httpMethod = "GET", response = String.class)
    public String goUploadPage() {
        return "upload";
    }

    @RequestMapping("/registerPage")
    @ApiOperation(value = "进入注册界面",
            httpMethod = "GET", response = String.class)
    public String goLogin() {
        return "register";
    }

    @RequestMapping("/index")
    @ApiOperation(value = "进入主页面", httpMethod = "GET", response = Model.class)
    public String goIndex(HttpServletRequest request, HttpServletResponse response, Model model) {
        userService.goIndexPage(request, response, model);
        User user = getUserSession.getUser(request);
        Configs configs = new Configs();
        if (user == null) {
            configs = configsMapper.selectByPrimaryKey(1);
        } else {
            configs = configsMapper.selectByPrimaryKey(user.getCoId());
        }
        session.setAttribute("config", configs);
        return "index";
    }

    @RequestMapping("/back")
    @ApiOperation(value = "进入后台页面",
            httpMethod = "GET", response = Model.class)
    public String goBack(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "page", defaultValue = "1") int page, Model model) {
        userService.goBackPage(request, response, page, model);
        return "blog";
    }

    @RequestMapping("/sign")
    @ApiOperation(value = "进入登录页面",
            httpMethod = "GET", response = String.class)
    public String goSigin(){
       
        return "sign";
    }

    @RequestMapping("/sendEmail")
    @ApiOperation(value = "发送验证码，并将验证码返回前端", notes = "targetEmail,目标用户的email",
            httpMethod = "POST", response = ServerResponse.class)
    @ResponseBody
    public ServerResponse sendEmail(String targetEmail, HttpServletRequest req) {
        logger.info("发送验证码");
        SendEmail send = new SendEmail();
        //发送成功则将验证码返回前台
        return send.sendEmail(targetEmail, req);
    }

    @RequestMapping("/checkLogin")
    @ApiOperation(value = "登录验证", notes = "需要参数:uEmail,uPwd,freeLogin",
            httpMethod = "POST", response = ServerResponse.class)
    @ResponseBody
    public ServerResponse checkLogin(String uEmail, String uPwd, boolean freeLogin, HttpServletRequest req, HttpServletResponse resp, Model model) {
        System.out.println("邮箱为：" + uEmail);
        return userService.checkLogin(uEmail, uPwd, req, resp, freeLogin, model);
    }

    @RequestMapping("/inquireEmail")
    @ResponseBody
    @ApiOperation(value = "动态查询用户是否已经存在用ajax请求",
            httpMethod = "POST", response = ServerResponse.class)
    public ServerResponse inquireEmail(String email) {
        logger.info("动态查询用户是否已经存在用ajax请求");
        return userService.inquireEmail(email);
    }

    @RequestMapping("/register")
    @ApiOperation(value = "用户的注册，", notes = "参数：uName,uPwd,uEmail，分别为:用户名，密码，邮箱",
            httpMethod = "POST", response = ServerResponse.class)
    @ResponseBody
    public ServerResponse register(User user, HttpServletRequest req, String code) {
        logger.info("用户注册");
        System.out.println(code);
        System.out.println(user.getuEmail());
        user.setuTime(new Date());
        return userService.register(user, req, code);
    }


    @RequestMapping("/updateUserByUser")
    @ApiOperation(value = "用户自己修改信息，", notes = "下面的所有的参数（uId不能修改）",
            httpMethod = "POST")

    public String updateUserByUser(User user) {
        System.out.println(userService.updateUser(user, request).isSuccess());
        System.out.println(user.getuName());
        return "redirect:personalData";
    }


    @RequestMapping("/loginOut")
    @ApiOperation(value = "用户注销登录", notes = "再次访问本网站时候需要重新输入密码",
            httpMethod = "POST", response = ServerResponse.class)
    @ResponseBody
    public ServerResponse loginOut(HttpServletRequest req, HttpServletResponse resp) {
        return userService.loginOut(req, resp);
    }

    @RequestMapping("/findPwd")
    @ApiOperation(value = "找回用户的密码", notes = "需要前台进行先发邮箱验证后才能将用户密码发到用户的邮箱里面",
            httpMethod = "POST", response = ServerResponse.class)
    @ResponseBody
    public ServerResponse findPwd(String email) {
        return userService.findPwd(email);
    }

    @RequestMapping("/uploadUhead")
    @ApiOperation(value = "上传用户的头像", notes = "用于用户修改自己的资料",
            httpMethod = "POST")
    public String uploadUhead(MultipartFile uHeaed, HttpServletRequest req) {
        userService.uploadHead(uHeaed, req);
        return "redirect:personalData";
    }

    @RequestMapping("/vipPage")
    @ApiOperation(value = "进入VIP页面", notes = "这个请求不需要任何的参数",
            httpMethod = "POST", response = ServerResponse.class)
    public String vipPage(Model model, HttpServletRequest request) {
        //将user添加到model里面
        getUserSession.addUserModel(request, model);
        List<Book> books = new ArrayList<>();
        model.addAttribute("vip", exchangeService.findExchange().getData());
        List<Serialize> serializes = new ArrayList<>();
        List<Serialize> recommentSerialize = serializeService.putawayList();
        for (int i = 0; i < 4; i++) {
            serializes.add(recommentSerialize.get(i));
        }
        model.addAttribute("recommendSerialize", serializes);
        return "vip";
    }

    @RequestMapping("/serialize")
    @ApiOperation(value = "进入小册页面", notes = "这个请求不需要任何的参数",
            httpMethod = "POST", response = ServerResponse.class)
    public String goSerializePage(Model model, HttpServletRequest request) {
        //将user添加到model里面
        getUserSession.addUserModel(request, model);
        //所有的书（连载）放到model里面
        List<Serialize> serializeList = serializeService.putawayList();
        List books = new ArrayList();
        Collections.reverse(serializeList);
        System.out.println("遍历出来的数据有多少条？" + serializeList.size());
        for (int i = 0; i < serializeList.size(); i++) {
            Serialize serialize = (Serialize) serializeList.get(i);
            books.add(new Book((User) userService.findUserById(serialize.getuId()).getData(), serialize));
            System.out.println(serialize);
        }
        model.addAttribute("book", books);
        return "book";
    }

    @RequestMapping("/readBook")
    @ApiOperation(value = "从小册点进书显示连载的具体信息（可以进行阅读)需要发送给我们连载的id",
            httpMethod = "GET", response = ServerResponse.class)
    public String readBook(Model model, HttpServletRequest request, long serializeId) {
        //将汇率放到model里面
        model.addAttribute("vip", exchangeService.findExchange().getData());
        //将user添加到model里面
        getUserSession.addUserModel(request, model);
        //将连载放入进去
        Serialize serialize = (Serialize) serializeService.findAllSerializeById(serializeId).getData();
        model.addAttribute("serialize", new ReadSerialize((User) userService.findUserById(serialize.getuId()).getData(), serialize));
        //将具体的连载章节放在model里面
        model.addAttribute("chapter", chapterService.getAllChapter(serializeId).getData());
        //关于这篇连载的评论
        model.addAttribute("UserComment", commentService.findCommentBySerialize(serializeId));
        boolean isBuy = false;
        if (orderMapper.isBy(getUserSession.getUser(request).getuId(), serializeId) != null) {
            isBuy = true;
        }
        model.addAttribute("isBuy", isBuy);
        return "detail";
    }

    @RequestMapping("/readChapter")
    @ApiOperation(value = "阅读章节",
            httpMethod = "POST", response = ServerResponse.class)
    public String readChapter(Model model, HttpServletRequest request, long chId) {
        //将user添加到model里面
        getUserSession.addUserModel(request, model);
        //获取user的id，判断用户是否购买该连载
        User user = getUserSession.getUser(request);
        List<Long> sid = orderService.findSidByUid(user.getuId());
        if (sid.contains(chId) || chId < 5) {
            model.addAttribute("chapter", chapterService.getChapterByChid(chId));
            return "detail";
        } else {
            return "book";
        }
    }

    @RequestMapping("/paidNotes")
    @ApiOperation(value = "进入已购内容页面", notes = "这个请求不需要任何的参数",
            httpMethod = "POST", response = ServerResponse.class)
    public String goPaidNotesPage(Model model, HttpServletRequest request) {
        //将user添加到model里面
        getUserSession.addUserModel(request, model);
        //所有的已购连载放到model里面
        User user = getUserSession.getUser(request);
        model.addAttribute("serialize", orderService.findOrderByUid(user.getuId()));
        return "paidNotes";
    }

    @ApiOperation(value = "根据用户id查询用的用户的信息.",
            httpMethod = "POST", response = ServerResponse.class)
    @ResponseBody
    @RequestMapping("/findUserById")
    public ServerResponse findUserById(long uId) {
        return userService.findUserById(uId);
    }

    @RequestMapping("/personalData")
    @ApiOperation(value = "显示个人信息页面",
            httpMethod = "POST", response = ServerResponse.class)
    public String personalPageData(HttpServletRequest request, Model model) {
        getUserSession.addUserModel(request, model);
        return "personalData";
    }

    @RequestMapping("/PersonalPage")
    @ApiOperation(value = "进入个人主页", httpMethod = "GET")
    public String PersonalPage(HttpServletRequest request, Model model) {
        //获取用户发表过的所有博客信息
        model.addAttribute("recommendBlog", blogService.getPersonPublicBlog(getUserSession.getUser(request).getuId()));
        //进行获取用户的获取赞的情况信息
        model.addAttribute("userMassage", userService.showPersonalMassage(request));
        return "personalIndex";
    }

    //进入别人页面进行观看
    @RequestMapping("/otherPersonaPage")
    @ApiOperation(value = "进入其他人的个人主页", httpMethod = "GET")
    public String otherPage(long uId, Model model) {
        //获取用户发表过的所有博客信息
        model.addAttribute("recommendBlog", blogService.getPersonPublicBlog(uId));
        //进行获取其他用户的
        System.out.println(userService.showOtherMassage(uId).getUser().getuName());
        model.addAttribute("userMassage", userService.showOtherMassage(uId));
        return "OtherIndex";
    }

}
